package com.fate.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fate.contant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Configuration
public class RouteConfig {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 路由存放token
     */
    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder){
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes.route("oauth-server-router",r -> r.path("/oauth/token")
        .filters(f->f.modifyResponseBody(String.class,String.class,
                (exchanges,s)  ->{
                //拿到登录响应值 s
                    JSONObject jsonObject = JSONUtil.parseObj(s);
                    String accessToken = jsonObject.getStr("access_token");
                    if (StringUtils.hasText(accessToken)){
                        //登录成功了
                        //拿到过期时间
                        Long expiresIn = jsonObject.getLong("expires_in");
                        //存入redis
                        redisTemplate.opsForValue().set(GatewayConstant.TOKEN_JWT_PREFIX+accessToken,"", Duration.ofSeconds(expiresIn));
                    }
                    return Mono.just(s);
                }) )
        .uri("lb://auth-server"));
        return routes.build();
    }
}
